import cloud from '@lafjs/cloud'
let dbName = "web-order"
const dbm = cloud.mongo.db

export async function changeOrderInfo(whereJson) {
  try {
    let res = await cloud.nw.db.findByWhereJson({
      dbName, whereJson,
    });

    //实付金额
    let payPrice = 0
    if (res.hasOwnProperty("pay_info")) {
      payPrice += (res.pay_info.pay_amount.total / 100)
    }
    if (res.hasOwnProperty("balance_pay_info")) {
      payPrice += (res.balance_pay_info.pay_amount.total / 100)
    }

    //优惠金额
    let discountPrice = 0
    if (res.hasOwnProperty("pay_discount_info")) {
      let array = res.pay_discount_info
      array.forEach(element => {
        discountPrice += (element.info.amount.refund / 100)
      });
    }

    //退款金额
    let refundPrice = 0
    if (res.hasOwnProperty("refund_info")) {
      if (res.refund_info.hasOwnProperty("refund_amount")) refundPrice += (res.refund_info.refund_amount.refund / 100)
    }
    if (res.hasOwnProperty("balance_refund_info")) refundPrice += (res.balance_refund_info.refund_amount.refund / 100)

    //订单金额
    let displayPrice = 0
    if (payPrice > Number(res.price)) {
      displayPrice = payPrice - discountPrice
    } else {
      displayPrice = Number(res.price) - discountPrice
    }
    let finalAmount = payPrice - discountPrice - refundPrice //最终金额
    //之前好像有点问题，重新赋值
    displayPrice = finalAmount

    let dataJson = { payPrice, discountPrice, displayPrice, finalAmount, refundPrice }

    //有优惠金额，且还有展示金额，则是优惠减免状态
    if (displayPrice && discountPrice) dataJson['status'] = 10
    //如果有实际支付 && 实际退款 && 实付金额 - 优惠 - 退款金额 = 0
    if (res.hasOwnProperty("pay_info") && res.hasOwnProperty("refund_info")) {
      if ((payPrice - discountPrice - refundPrice) == 0) dataJson['status'] = 4
    }

    await cloud.nw.db.update({
      dbName,
      whereJson,
      dataJson
    });
  } catch (error) {
    console.log("有问题的订单是" + whereJson._id)
  }
}

//单独生成一个订单用户基础信息
export async function setOrderBaseInfo(_id) {
  let res = await cloud.nw.db.findByWhereJson({
    dbName: "web-order", whereJson: { _id },
  });
  await cloud.nw.db.update({
    dbName: "web-order",
    whereJson: { _id },
    dataJson: { orderUserInfo: res.approvalContent.model }
  });
}


//设置中间页里面的学员状态
export async function setMoXueYuanOrderUserInfo(userId) {
  let array = await dbm.collection("moxueyuan-order-list").find({ userId }).project({ _id: 1 }).toArray()
  //console.log("嘻嘻嘻", res)
  let resp = await getMoXueYuanData("moxueyuan-user-detail", userId, array[0].mobile,
    { disabled: 1, addTime: 1, tagList: 1, name: 1, mobile: 1, userid: 1 }
  )
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    await cloud.nw.db.update({
      dbName: "moxueyuan-order-list",
      whereJson: { _id: element._id, },
      dataJson: { user_detail_info: resp }
    });
  }
  //console.log("查询到的值", resp)
}


//设置订单的魔学院学习状态
export async function setOrderLearningStatus() {
  await dbm.collection("moxueyuan-order-list").deleteMany({})

  let year = cloud.utils.dateTimeFormat(Date.now(), 'year')
  let isDiscount = []//优惠减免过的订单号

  let userTrains = await dbm.collection("moxueyuan-user-train").find({}).project({ trainId: 1, status: 1, mobile: 1, trainContent: 1 }).toArray()
  let trainTags = await dbm.collection("admin-train-tag").find({}).project({ tagId: 1, trainId: 1, index: 1 }).toArray()
  let course = await dbm.collection("web-course").find({}).project({ lessonContent: 1 }).toArray()

  //魔学院有哪些学员，且账号是开启状态
  let moUsers = await dbm.collection("moxueyuan-user-detail").find({}).project({ mobile: 1, userid: 1 }).toArray()

  let mobiles = []
  let userIds = []
  moUsers.forEach(element => {
    mobiles.push(element.mobile);
    userIds.push(element.userid)
  });

  let whereJson = {
    $or: [
      { mobile: { $in: mobiles } },
      { userId: { $in: userIds } }
    ],
    status: { $in: [2, 7, 10] },
  }

  let orders = await dbm.collection("web-order").find(whereJson).project({
    approvalContent: 1, mobile: 1, _add_time: 1, out_trade_no: 1, status: 1, curriculum_id: 1, userId: 1, isMoXueYuanPublished: 1
  }).toArray()
  console.log("订单数量", orders.length)

  for (let index = 0; index < orders.length; index++) {
    const element = orders[index];
    element.createOrderTime = element._add_time//创建订单的时间
    if (element.status == 10) isDiscount.push(element.out_trade_no)//将优惠减免的订单号都存下来

    let tags = []
    let courseTags = []  //该订单里面有哪些课程tag
    let selectLesson = element.approvalContent.selectLesson || [];
    let subscript = cloud.utils.findIndexByField(course, "_id", element.curriculum_id)
    if (subscript != -1) {
      let courseContent = course[subscript].lessonContent
      selectLesson.forEach(element => {
        let sub = cloud.utils.findIndexByField(courseContent, "id", element.id)
        if (sub != -1 && courseContent[sub].tag) {
          courseTags.push(courseContent[sub].tag)
        }
      });
    }
    let moxueyuanInfo = await getMoXueYuanData("moxueyuan-user-detail", element.userId, element.mobile,
      { tag: 1 }
    )
    //魔学院里的最新标签
    moxueyuanInfo.tag.forEach(item => {
      if (courseTags.includes(item)) tags.push(item)
    });
    element.tags = tags

    //这个学员一共有哪些培训项目
    let trainInfo = []
    userTrains.forEach(item => {
      //翻译一下状态
      item.trainContent.forEach(k => {
        k.learningStatusFormat = status_format(k.learningStatus)
      });

      if (item.mobile == element.mobile) {
        let examids = []
        item.trainContent.forEach(el => {
          if (el.examid) examids.push(el.examid)
        });
        trainInfo.push({
          trainId: item.trainId, status: item.status, examids, trainContent: item.trainContent
        })
      }
    });

    let tagsStatus = []

    tags.forEach(item => {
      let obj = { tagId: item, mobile: element.mobile }
      let current = cloud.utils.findIndexByField(trainTags, "tagId", item)
      if (current != -1) {
        obj["trainId"] = trainTags[current].trainId
        obj["index"] = Number(trainTags[current].index)

        let subscript = cloud.utils.findIndexByField(trainInfo, "trainId", obj["trainId"])
        if (subscript != -1) {
          obj["status"] = trainInfo[subscript].status
          obj["statusName"] = status_format(obj["status"])
          obj["examids"] = trainInfo[subscript].examids
          obj['trainContent'] = trainInfo[subscript].trainContent
        }
      }
      tagsStatus.push(obj)
    });
    element.tagsStatus = tagsStatus

    //培训完成状态数量
    let trainTotal = 0
    tagsStatus.forEach(item => {
      if (item.status && item.status == 2) trainTotal++
    });
    element.trainTotal = trainTotal

    //培训完成状态
    if (trainTotal && (trainTotal >= tags.length)) {
      element.trainCompleted = 1
    } else {
      element.trainCompleted = 0
    }

    //更新订单
    // let query = cloud.utils.deepcopy(element)
    // await cloud.utils.updateData("web-order", query)
  }

  console.log("优惠订单", isDiscount.length, isDiscount.includes("1751534021863522"))

  let newOrders = []
  for (let index = 0; index < orders.length; index++) {
    const element = orders[index];
    processOrder(element)
  }

  //操作数组
  function processOrder(item) {
    newOrders.push(item)
    let tags = []
    let tagsStatus = []
    let orderIds = []
    newOrders.forEach(element => {
      let preYear = cloud.utils.dateTimeFormat(element._add_time, 'year')
      let nextYear = cloud.utils.dateTimeFormat(item._add_time, 'year')
      if ((element.userId == item.userId) && (element.curriculum_id == item.curriculum_id) && (preYear == nextYear)) {
        tags.push(...element.tags)
        tagsStatus.push(...element.tagsStatus)
        orderIds.push(element._id)
      }
    });
    let newTags = cloud.utils.unique(tags)
    let newTagsStatus = cloud.utils.arrayUnique2(tagsStatus, "tagId")
    //培训完成状态数量
    let trainTotal = 0
    newTagsStatus.forEach(item => {
      if (item.status && item.status == 2) trainTotal++
    });
    //培训完成状态
    let trainCompleted = (trainTotal && (trainTotal >= newTags.length)) ? 1 : 0
    orderIds.forEach(element => {
      let current = cloud.utils.findIndexByField(newOrders, "_id", element)
      if (current != -1) {
        newOrders[current].tags = newTags
        newOrders[current].tagsStatus = newTagsStatus
        newOrders[current].trainTotal = trainTotal
        newOrders[current].trainCompleted = trainCompleted
      }
    });
  }

  newOrders.forEach(element => {
    element.year = cloud.utils.dateTimeFormat(element.createOrderTime, 'year')
  });
  let integrationArr = deDuplicateWithAggregate(newOrders, "userId", "curriculum_id", "year", "out_trade_no")
  console.log("筛选之后的值", integrationArr.length)

  //更新魔学院-订单列表
  for (let index = 0; index < integrationArr.length; index++) {
    const element = integrationArr[index];
    element.out_trade_no_string = element.out_trade_no.toString()//订单号转字符串

    element.published = 1 //默认公布的数据值都是1

    //如果有公布学时，和当前学时不匹配的情况
    if (element.isMoXueYuanPublished && element.isMoXueYuanPublished.currentTrainTotal && (element.isMoXueYuanPublished.currentTrainTotal != element.trainTotal)) { element.published = 2 }

    //考试合格
    element.user_count_info = await getMoXueYuanData("moxueyuan-user-count", element.userId, element.mobile,
      { passExam: 1 })

    //是否禁用 添加时间 标签列表
    element.user_detail_info = await getMoXueYuanData("moxueyuan-user-detail", element.userId, element.mobile,
      { disabled: 1, addTime: 1, tagList: 1, name: 1, mobile: 1, userid: 1 }
    )

    //考试分数
    let examids = []
    let examUsers_info = []
    element.tagsStatus.forEach(item => { if (item.examids) examids.push(...item.examids) });
    examids = cloud.utils.unique([...examids])
    let examUsers = await getMoXueYuanData("moxueyuan-examUsers-statistics", element.userId, element.mobile,
      { stateValue: 1, score: 1, examId: 1, examName: 1 }, "array")

    examids.forEach(item => {
      let cur = cloud.utils.findIndexByField(examUsers, "examId", item)
      if (cur != -1) examUsers_info.push(examUsers[cur])
    });
    element.examUsers_info = examUsers_info

    //最后活跃时间
    element.user_statistics_info = await getMoXueYuanData("moxueyuan-user-statistics", element.userId, element.mobile,
      { lastActiveTime: 1, department: 1, totalLearningTime: 1, completedTrain: 1 })

    //课程名称
    element.course_info = await cloud.nw.db.findByWhereJson({ dbName: "web-course", whereJson: { _id: element.curriculum_id }, fieldJson: { name: 1 } })

    //数据新增时间
    element.dataUpdateTime = Date.now()

    //里面有优惠减免的订单号吗
    let hasDiscount = false
    element.out_trade_no.forEach(item => {
      if (isDiscount.includes(item)) hasDiscount = true
    });
    element.hasDiscount = hasDiscount
    //await addOrEdit(element)
  }

  integrationArr.forEach(element => {
    element.isRepeat = 0 //默认没有报名多门课程
  });

  //批量新增数据
  await dbm.collection('moxueyuan-order-list').insertMany(markRepeatedItems(integrationArr, "userId", "year"))

  //状态翻译
  function status_format(e) {
    let status2 = [
      { name: "未参加", value: 0 },
      { name: "进行中", value: 1 },
      { name: "已完成", value: 2 },
      { name: "未完成", value: 3 },
    ];
    let index = cloud.utils.findIndexByField(status2, "value", e);
    return index != -1 ? status2[index].name : "";
  }

  async function addOrEdit(element) {
    let res = await cloud.nw.db.findByWhereJson({
      dbName: "moxueyuan-order-list", whereJson: { _id: element._id },
    });
    if (res && res._id) {
      await cloud.utils.updateData("moxueyuan-order-list", element)
    } else {
      await dbm.collection('moxueyuan-order-list').insertOne(element)
    }
  }


  /**
 * 根据多个键组合去重，并聚合保留指定字段的值
 * @param {Array} data - 原始对象数组
 * @param {string} key1 - 第一个去重键
 * @param {string} key2 - 第二个去重键
 * @param {string} key3 - 第三个去重键
 * @param {string} keepKey - 需聚合保留的字段名
 * @returns {Array} - 去重后的新数组
 */
  function deDuplicateWithAggregate(data, key1, key2, key3, keepKey) {
    // 1. 使用Map存储唯一键组合与对应数据
    const map = new Map();

    data.forEach(item => {
      // 2. 生成组合键（确保键顺序一致）
      const compositeKey = `${item[key1]}|${item[key2]}|${item[key3]}`;

      if (map.has(compositeKey)) {
        // 3. 键已存在：聚合keepKey的值
        const existing = map.get(compositeKey);
        existing[keepKey] = [].concat(existing[keepKey], item[keepKey]);
      } else {
        // 4. 键不存在：创建新条目并初始化keepKey为数组
        const newItem = { ...item };
        newItem[keepKey] = [item[keepKey]];
        map.set(compositeKey, newItem);
      }
    });

    // 5. 返回去重后的结果数组
    return Array.from(map.values());
  }
}


//去对应的魔学院数组里面取值
async function getMoXueYuanData(dbName, userid, mobile, project, type = "object") {
  if (type == "array") {
    let aa = await dbm.collection(dbName).find({ userid }).project(project).toArray()
    if (aa.length) return aa
    let bb = await dbm.collection(dbName).find({ mobile }).project(project).toArray()
    return bb
  } else {
    let res = await cloud.nw.db.findByWhereJson({ dbName, whereJson: { userid }, fieldJson: project })
    if (res && res._id) return res
    let resp = await cloud.nw.db.findByWhereJson({ dbName, whereJson: { mobile }, fieldJson: project })
    if (resp && resp._id) return resp
  }
}

//如果有一个学员同时报名了多个不同的课程，则打上标记
function markRepeatedItems(jsonArray, key1, key2) {
  // 首先，我们需要检查传入的参数是否有效
  if (!Array.isArray(jsonArray)) {
    throw new Error('第一个参数必须是数组');
  }
  if (typeof key1 !== 'string' || typeof key2 !== 'string') {
    throw new Error('键名必须是字符串');
  }

  // 创建一个Map来记录每个键组合出现的次数
  const countMap = new Map();

  // 第一次遍历：统计每个键组合出现的次数
  for (const item of jsonArray) {
    // 确保当前对象具有这两个键
    if (item && item.hasOwnProperty(key1) && item.hasOwnProperty(key2)) {
      const combinedKey = `${item[key1]}|${item[key2]}`; // 使用特殊字符组合两个键的值

      if (countMap.has(combinedKey)) {
        countMap.set(combinedKey, countMap.get(combinedKey) + 1);
      } else {
        countMap.set(combinedKey, 1);
      }
    }
  }

  // 第二次遍历：创建新数组并为重复出现的对象添加 isRepeat 字段
  const resultArray = jsonArray.map(item => {
    // 浅拷贝原对象
    const newItem = { ...item };

    // 只有当对象拥有这两个键时才进行检查
    if (newItem && newItem.hasOwnProperty(key1) && newItem.hasOwnProperty(key2)) {
      const combinedKey = `${newItem[key1]}|${newItem[key2]}`;

      // 如果该键组合出现次数大于1，则标记为重复
      if (countMap.get(combinedKey) > 1) {
        newItem.isRepeat = 1;
      }
    }

    return newItem;
  });

  return resultArray;
}

